﻿using MODEL;
using SysCommon;
using SysController;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace CurrencyRateService
{
    public partial class CurrencyService : ServiceBase
    {
        public CurrencyService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {

        }


        protected override void OnStop()
        {
        }

        public string GuidFiled { get; set; }

        /// <summary>
        /// 每天更新一次结算汇率
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Currency_UpdateRate_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (!this.Currency_UpdateRate.IsTime(8, -1)) return;
            HoFan.Aliexpress.Common.Utility.Log.Write("【START】每天8点更新一次结算汇率");
            try
            {
                int res = CurrencyRateController.UpdateRate();
                HoFan.Aliexpress.Common.Utility.Log.Write(string.Format("【Count:】{0}", res));
            }
            catch (Exception ex)
            {
                HoFan.Aliexpress.Common.Utility.Log.Write(string.Format("【Error:】每天更新一次结算汇率   \r\n {0}", ex));
            }
        }

        /// <summary>
        /// 每天对汇率波动分析
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Currency_RateFluctuation_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (!this.Currency_RateFluctuation.IsTime(20, -1)) return;
            HoFan.Aliexpress.Common.Utility.Log.Write("【START】每天20点对汇率波动分析");
            List<RateOfExchange> list1 = null, list0 = null; List<Currency> listCurrency = null;
            try
            {
                listCurrency = CurrencyRateController.GetCurrency();
                HoFan.Aliexpress.Common.Utility.Log.Write("【INFO】 GetCurrency : " + listCurrency.Count);
            }
            catch (Exception ex)
            {
                HoFan.Aliexpress.Common.Utility.Log.Write(ex.Message);
            }

            try
            {
                list0 = CurrencyRateController.GetRateOfExchange(-1, false);
                HoFan.Aliexpress.Common.Utility.Log.Write("【INFO】 GetRateOfExchange : list0:" + list0.Count);
            }
            catch (Exception ex)
            {
                HoFan.Aliexpress.Common.Utility.Log.Write(ex.Message);
            }
            try
            {
                list1 = CurrencyRateController.GetRateOfExchange(-1, true);
                HoFan.Aliexpress.Common.Utility.Log.Write("【INFO】 GetRateOfExchange :  list1:" + list1.Count);
            }
            catch (Exception ex)
            {
                HoFan.Aliexpress.Common.Utility.Log.Write(ex.Message);
            }
            try
            {
                Dictionary<int, decimal> dict = CurrencyRateController.GetRate();

                HoFan.Aliexpress.Common.Utility.Log.Write("【INFO】 Dictionary<int, decimal> : dict:" + dict.Count);

                List<RateFluctuationModel> list = CurrencyRateController.RateFluctuation(list1, list0, dict);
                 
                StringBuilder sb = new StringBuilder();
                List<int> listCurrencyId = new List<int>();
                sb.Append("<TABLE border=2 cellSpacing=2 cellPadding=1 width=\"50%\" cols=2>");
                sb.Append(@"<TR><TD>币种编号</TD><TD>币种</TD><TD>定价汇率</TD><TD>定价汇率波动</TD><TD>时实汇率</TD><TD>结算汇率</TD><TD>结算汇率波动</TD><TD>时间</TD></TR>");
                foreach (var item in list)
                {
                    if (item.Fluctuation1 >= 0.03m || item.Fluctuation1 <= -0.03m) listCurrencyId.Add(item.CurrencyID);
                    string CurrencyDesc = listCurrency.Where(s => s.CurrencyID == item.CurrencyID).FirstOrDefault().CurrencyDesc;
                    sb.Append(string.Format("<TR><TD>{7}</TD><TD>{6}</TD><TD>{0}</TD><TD>{1}</TD><TD  Style=\"Color:red \">{2}</TD><TD>{3}</TD><TD>{4}</TD><TD>{5}</TD></TR>", item.Rate1, item.Fluctuation1, item.Rate, item.Rate0, item.Fluctuation0, item.AcctionTime, CurrencyDesc,item.CurrencyID));
                }
                sb.Append("</TABLE>");

                string str = UpdateRateByFluctuation(listCurrencyId);
                if(!string.IsNullOrEmpty(str))
                sb.Append(string.Format("<BR><BR>  以下币种波动 超过 3% ，已根据 6 天汇率平均值 更新 【定价汇率】，请注意对该币种的价格 刷新！<BR><BR>{0}", str));

                SendEmail("valeb@sina.cn", "汇率波动信息", sb.ToString());
                HoFan.Aliexpress.Common.Utility.Log.Write("【END】");
            }
            catch (Exception ex)
            {
                HoFan.Aliexpress.Common.Utility.Log.Write(ex.Message);
            }
        }

        /// <summary>
        /// 每小时对实时汇率备份
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Currency_BackRate_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            HoFan.Aliexpress.Common.Utility.Log.Write("【START】每小时对实时汇率备份");
            try
            {
                int res = CurrencyRateController.BackRateOfExchange();
                HoFan.Aliexpress.Common.Utility.Log.Write(string.Format("【Count:】{0}", res));
            }
            catch (Exception ex)
            {
                HoFan.Aliexpress.Common.Utility.Log.Write(string.Format("【Error:】每小时对实时汇率备份   \r\n {0}", ex));
            }
        }

        /// <summary>
        /// 每4小时对汇率分析
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Currency_AnalysisRate_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            GuidFiled = Guid.NewGuid().ToString().Replace("-", "");
            HoFan.Aliexpress.Common.Utility.Log.Write("【START】每4小时对汇率分析 VERSION:   " + GuidFiled);
            try
            {
                List<Currency> listCurrency = CurrencyRateController.GetCurrency();
                int res = CurrencyRateController.AnalysisExchangeRate(GuidFiled, listCurrency.Select(s => s.CurrencyID).ToList());
                HoFan.Aliexpress.Common.Utility.Log.Write(string.Format("【Count:】{0}", res));
            }
            catch (Exception ex)
            {
                HoFan.Aliexpress.Common.Utility.Log.Write(string.Format("【Error:】每4小时对汇率分析 {0}  \r\n {1}", GuidFiled, ex));
            }
        }



        private void SendEmail(string MailRecipient, string MailSubject, string MailContent)
        {
            Email.SMTPServer = "smtp.sina.cn";
            Email.SMTPPort = 25;
            Email.E_MailAddress = "valeb@sina.cn";
            Email.E_MailPassword = "2580203./*";
            Email.SendHtmlEmail(MailRecipient, MailSubject, MailContent);
        }

        private string UpdateRateByFluctuation(List<int> listCurrencyId)
        {
            string arr = string.Join(",", listCurrencyId);
            if (listCurrencyId != null && GuidFiled != null)
            {

                HoFan.Aliexpress.Common.Utility.Log.Write("【INFO】 汇率波动超过 3% ，修改定价汇率");
                int res = CurrencyRateController.UpdateRate(listCurrencyId, GuidFiled);
                HoFan.Aliexpress.Common.Utility.Log.Write(string.Format("【INFO】 采用 {0} 版本，修改 币种 {1}   完成 {2} 条", GuidFiled, arr, listCurrencyId.Count));
            }
            else if (listCurrencyId == null || GuidFiled == null)
            {
                HoFan.Aliexpress.Common.Utility.Log.Write(string.Format("【INFO】 汇率波动 修改条件有缺失 version:{0}  ; currencyId:{1}  ", GuidFiled, arr));
            }
            return arr;
        }

    }
}